home *** CD-ROM | disk | FTP | other *** search
/ Freelog 125 / Freelog_MarsAvril2015_No125.iso / Musique / Quod Libet / quodlibet-3.3.0-portable.exe / quodlibet-3.3.0-portable / data / bin / _strptime.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2014-12-31  |  14KB  |  428 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.7)
  3.  
  4. '''Strptime-related classes and functions.
  5.  
  6. CLASSES:
  7.     LocaleTime -- Discovers and stores locale-specific time information
  8.     TimeRE -- Creates regexes for pattern matching a string of text containing
  9.                 time information
  10.  
  11. FUNCTIONS:
  12.     _getlang -- Figure out what language is being used for the locale
  13.     strptime -- Calculates the time struct represented by the passed-in string
  14.  
  15. '''
  16. import time
  17. import locale
  18. import calendar
  19. from re import compile as re_compile
  20. from re import IGNORECASE
  21. from re import escape as re_escape
  22. from datetime import date as datetime_date
  23.  
  24. try:
  25.     from thread import allocate_lock as _thread_allocate_lock
  26. except:
  27.     from dummy_thread import allocate_lock as _thread_allocate_lock
  28.  
  29. __all__ = []
  30.  
  31. def _getlang():
  32.     return locale.getlocale(locale.LC_TIME)
  33.  
  34.  
  35. class LocaleTime(object):
  36.     '''Stores and handles locale-specific information related to time.
  37.  
  38.     ATTRIBUTES:
  39.         f_weekday -- full weekday names (7-item list)
  40.         a_weekday -- abbreviated weekday names (7-item list)
  41.         f_month -- full month names (13-item list; dummy value in [0], which
  42.                     is added by code)
  43.         a_month -- abbreviated month names (13-item list, dummy value in
  44.                     [0], which is added by code)
  45.         am_pm -- AM/PM representation (2-item list)
  46.         LC_date_time -- format string for date/time representation (string)
  47.         LC_date -- format string for date representation (string)
  48.         LC_time -- format string for time representation (string)
  49.         timezone -- daylight- and non-daylight-savings timezone representation
  50.                     (2-item list of sets)
  51.         lang -- Language used by instance (2-item tuple)
  52.     '''
  53.     
  54.     def __init__(self):
  55.         '''Set all attributes.
  56.  
  57.         Order of methods called matters for dependency reasons.
  58.  
  59.         The locale language is set at the offset and then checked again before
  60.         exiting.  This is to make sure that the attributes were not set with a
  61.         mix of information from more than one locale.  This would most likely
  62.         happen when using threads where one thread calls a locale-dependent
  63.         function while another thread changes the locale while the function in
  64.         the other thread is still running.  Proper coding would call for
  65.         locks to prevent changing the locale while locale-dependent code is
  66.         running.  The check here is done in case someone does not think about
  67.         doing this.
  68.  
  69.         Only other possible issue is if someone changed the timezone and did
  70.         not call tz.tzset .  That is an issue for the programmer, though,
  71.         since changing the timezone is worthless without that call.
  72.  
  73.         '''
  74.         self.lang = _getlang()
  75.         self._LocaleTime__calc_weekday()
  76.         self._LocaleTime__calc_month()
  77.         self._LocaleTime__calc_am_pm()
  78.         self._LocaleTime__calc_timezone()
  79.         self._LocaleTime__calc_date_time()
  80.         if _getlang() != self.lang:
  81.             raise ValueError('locale changed during initialization')
  82.  
  83.     
  84.     def __pad(self, seq, front):
  85.         seq = list(seq)
  86.         if front:
  87.             seq.insert(0, '')
  88.         else:
  89.             seq.append('')
  90.         return seq
  91.  
  92.     
  93.     def __calc_weekday(self):
  94.         a_weekday = [ calendar.day_abbr[i].lower() for i in range(7) ]
  95.         f_weekday = [ calendar.day_name[i].lower() for i in range(7) ]
  96.         self.a_weekday = a_weekday
  97.         self.f_weekday = f_weekday
  98.  
  99.     
  100.     def __calc_month(self):
  101.         a_month = [ calendar.month_abbr[i].lower() for i in range(13) ]
  102.         f_month = [ calendar.month_name[i].lower() for i in range(13) ]
  103.         self.a_month = a_month
  104.         self.f_month = f_month
  105.  
  106.     
  107.     def __calc_am_pm(self):
  108.         am_pm = []
  109.         for hour in (1, 22):
  110.             time_tuple = time.struct_time((1999, 3, 17, hour, 44, 55, 2, 76, 0))
  111.             am_pm.append(time.strftime('%p', time_tuple).lower())
  112.         
  113.         self.am_pm = am_pm
  114.  
  115.     
  116.     def __calc_date_time(self):
  117.         time_tuple = time.struct_time((1999, 3, 17, 22, 44, 55, 2, 76, 0))
  118.         date_time = [
  119.             None,
  120.             None,
  121.             None]
  122.         date_time[0] = time.strftime('%c', time_tuple).lower()
  123.         date_time[1] = time.strftime('%x', time_tuple).lower()
  124.         date_time[2] = time.strftime('%X', time_tuple).lower()
  125.         replacement_pairs = [
  126.             ('%', '%%'),
  127.             (self.f_weekday[2], '%A'),
  128.             (self.f_month[3], '%B'),
  129.             (self.a_weekday[2], '%a'),
  130.             (self.a_month[3], '%b'),
  131.             (self.am_pm[1], '%p'),
  132.             ('1999', '%Y'),
  133.             ('99', '%y'),
  134.             ('22', '%H'),
  135.             ('44', '%M'),
  136.             ('55', '%S'),
  137.             ('76', '%j'),
  138.             ('17', '%d'),
  139.             ('03', '%m'),
  140.             ('3', '%m'),
  141.             ('2', '%w'),
  142.             ('10', '%I')]
  143.         replacement_pairs.extend([ (tz, '%Z') for tz_values in self.timezone for tz in tz_values ])
  144.         for offset, directive in ((0, '%c'), (1, '%x'), (2, '%X')):
  145.             current_format = date_time[offset]
  146.             for old, new in replacement_pairs:
  147.                 if old:
  148.                     current_format = current_format.replace(old, new)
  149.                     continue
  150.             time_tuple = time.struct_time((1999, 1, 3, 1, 1, 1, 6, 3, 0))
  151.             if '00' in time.strftime(directive, time_tuple):
  152.                 U_W = '%W'
  153.             else:
  154.                 U_W = '%U'
  155.             date_time[offset] = current_format.replace('11', U_W)
  156.         
  157.         self.LC_date_time = date_time[0]
  158.         self.LC_date = date_time[1]
  159.         self.LC_time = date_time[2]
  160.  
  161.     
  162.     def __calc_timezone(self):
  163.         
  164.         try:
  165.             time.tzset()
  166.         except AttributeError:
  167.             pass
  168.  
  169.         no_saving = frozenset([
  170.             'utc',
  171.             'gmt',
  172.             time.tzname[0].lower()])
  173.         if time.daylight:
  174.             has_saving = frozenset([
  175.                 time.tzname[1].lower()])
  176.         else:
  177.             has_saving = frozenset()
  178.         self.timezone = (no_saving, has_saving)
  179.  
  180.  
  181.  
  182. class TimeRE(dict):
  183.     '''Handle conversion from format directives to regexes.'''
  184.     
  185.     def __init__(self, locale_time = None):
  186.         '''Create keys/values.
  187.  
  188.         Order of execution is important for dependency reasons.
  189.  
  190.         '''
  191.         if locale_time:
  192.             self.locale_time = locale_time
  193.         else:
  194.             self.locale_time = LocaleTime()
  195.         base = super(TimeRE, self)
  196.         base.__init__({
  197.             'd': '(?P<d>3[0-1]|[1-2]\\d|0[1-9]|[1-9]| [1-9])',
  198.             'f': '(?P<f>[0-9]{1,6})',
  199.             'H': '(?P<H>2[0-3]|[0-1]\\d|\\d)',
  200.             'I': '(?P<I>1[0-2]|0[1-9]|[1-9])',
  201.             'j': '(?P<j>36[0-6]|3[0-5]\\d|[1-2]\\d\\d|0[1-9]\\d|00[1-9]|[1-9]\\d|0[1-9]|[1-9])',
  202.             'm': '(?P<m>1[0-2]|0[1-9]|[1-9])',
  203.             'M': '(?P<M>[0-5]\\d|\\d)',
  204.             'S': '(?P<S>6[0-1]|[0-5]\\d|\\d)',
  205.             'U': '(?P<U>5[0-3]|[0-4]\\d|\\d)',
  206.             'w': '(?P<w>[0-6])',
  207.             'y': '(?P<y>\\d\\d)',
  208.             'Y': '(?P<Y>\\d\\d\\d\\d)',
  209.             'A': self._TimeRE__seqToRE(self.locale_time.f_weekday, 'A'),
  210.             'a': self._TimeRE__seqToRE(self.locale_time.a_weekday, 'a'),
  211.             'B': self._TimeRE__seqToRE(self.locale_time.f_month[1:], 'B'),
  212.             'b': self._TimeRE__seqToRE(self.locale_time.a_month[1:], 'b'),
  213.             'p': self._TimeRE__seqToRE(self.locale_time.am_pm, 'p'),
  214.             'Z': self._TimeRE__seqToRE((lambda .0: pass)(self.locale_time.timezone), 'Z'),
  215.             '%': '%' })
  216.         base.__setitem__('W', base.__getitem__('U').replace('U', 'W'))
  217.         base.__setitem__('c', self.pattern(self.locale_time.LC_date_time))
  218.         base.__setitem__('x', self.pattern(self.locale_time.LC_date))
  219.         base.__setitem__('X', self.pattern(self.locale_time.LC_time))
  220.  
  221.     
  222.     def __seqToRE(self, to_convert, directive):
  223.         """Convert a list to a regex string for matching a directive.
  224.  
  225.         Want possible matching values to be from longest to shortest.  This
  226.         prevents the possibility of a match occurring for a value that also
  227.         a substring of a larger value that should have matched (e.g., 'abc'
  228.         matching when 'abcdef' should have been the match).
  229.  
  230.         """
  231.         to_convert = sorted(to_convert, key = len, reverse = True)
  232.         for value in to_convert:
  233.             if value != '':
  234.                 break
  235.                 continue
  236.             return ''
  237.             regex = '|'.join((lambda .0: pass)(to_convert))
  238.             regex = '(?P<%s>%s' % (directive, regex)
  239.             return '%s)' % regex
  240.  
  241.     
  242.     def pattern(self, format):
  243.         '''Return regex pattern for the format string.
  244.  
  245.         Need to make sure that any characters that might be interpreted as
  246.         regex syntax are escaped.
  247.  
  248.         '''
  249.         processed_format = ''
  250.         regex_chars = re_compile('([\\\\.^$*+?\\(\\){}\\[\\]|])')
  251.         format = regex_chars.sub('\\\\\\1', format)
  252.         whitespace_replacement = re_compile('\\s+')
  253.         format = whitespace_replacement.sub('\\s+', format)
  254.         while '%' in format:
  255.             directive_index = format.index('%') + 1
  256.             processed_format = '%s%s%s' % (processed_format, format[:directive_index - 1], self[format[directive_index]])
  257.             format = format[directive_index + 1:]
  258.         return '%s%s' % (processed_format, format)
  259.  
  260.     
  261.     def compile(self, format):
  262.         '''Return a compiled re object for the format string.'''
  263.         return re_compile(self.pattern(format), IGNORECASE)
  264.  
  265.  
  266. _cache_lock = _thread_allocate_lock()
  267. _TimeRE_cache = TimeRE()
  268. _CACHE_MAX_SIZE = 5
  269. _regex_cache = { }
  270.  
  271. def _calc_julian_from_U_or_W(year, week_of_year, day_of_week, week_starts_Mon):
  272.     '''Calculate the Julian day based on the year, week of the year, and day of
  273.     the week, with week_start_day representing whether the week of the year
  274.     assumes the week starts on Sunday or Monday (6 or 0).'''
  275.     first_weekday = datetime_date(year, 1, 1).weekday()
  276.     if not week_starts_Mon:
  277.         first_weekday = (first_weekday + 1) % 7
  278.         day_of_week = (day_of_week + 1) % 7
  279.     week_0_length = (7 - first_weekday) % 7
  280.     if week_of_year == 0:
  281.         return 1 + day_of_week - first_weekday
  282.     days_to_week = None + 7 * (week_of_year - 1)
  283.     return 1 + days_to_week + day_of_week
  284.  
  285.  
  286. def _strptime(data_string, format = '%a %b %d %H:%M:%S %Y'):
  287.     '''Return a time struct based on the input string and the format string.'''
  288.     global _TimeRE_cache
  289.     with _cache_lock:
  290.         if _getlang() != _TimeRE_cache.locale_time.lang:
  291.             _TimeRE_cache = TimeRE()
  292.             _regex_cache.clear()
  293.         if len(_regex_cache) > _CACHE_MAX_SIZE:
  294.             _regex_cache.clear()
  295.         locale_time = _TimeRE_cache.locale_time
  296.         format_regex = _regex_cache.get(format)
  297.         if not format_regex:
  298.             
  299.             try:
  300.                 format_regex = _TimeRE_cache.compile(format)
  301.             except KeyError:
  302.                 err = None
  303.                 bad_directive = err.args[0]
  304.                 if bad_directive == '\\':
  305.                     bad_directive = '%'
  306.                 del err
  307.                 raise ValueError("'%s' is a bad directive in format '%s'" % (bad_directive, format))
  308.             except IndexError:
  309.                 raise ValueError("stray %% in format '%s'" % format)
  310.  
  311.             _regex_cache[format] = format_regex
  312.     found = format_regex.match(data_string)
  313.     if not found:
  314.         raise ValueError('time data %r does not match format %r' % (data_string, format))
  315.     if len(data_string) != found.end():
  316.         raise ValueError('unconverted data remains: %s' % data_string[found.end():])
  317.     year = None
  318.     month = day = 1
  319.     hour = minute = second = fraction = 0
  320.     tz = -1
  321.     week_of_year = -1
  322.     week_of_year_start = -1
  323.     weekday = julian = -1
  324.     found_dict = found.groupdict()
  325.     for group_key in found_dict.iterkeys():
  326.         if group_key == 'y':
  327.             year = int(found_dict['y'])
  328.             if year <= 68:
  329.                 year += 2000
  330.             else:
  331.                 year += 1900
  332.         if group_key == 'Y':
  333.             year = int(found_dict['Y'])
  334.             continue
  335.         if group_key == 'm':
  336.             month = int(found_dict['m'])
  337.             continue
  338.         if group_key == 'B':
  339.             month = locale_time.f_month.index(found_dict['B'].lower())
  340.             continue
  341.         if group_key == 'b':
  342.             month = locale_time.a_month.index(found_dict['b'].lower())
  343.             continue
  344.         if group_key == 'd':
  345.             day = int(found_dict['d'])
  346.             continue
  347.         if group_key == 'H':
  348.             hour = int(found_dict['H'])
  349.             continue
  350.         if group_key == 'I':
  351.             hour = int(found_dict['I'])
  352.             ampm = found_dict.get('p', '').lower()
  353.             if ampm in ('', locale_time.am_pm[0]) or hour == 12:
  354.                 hour = 0
  355.             
  356.         elif ampm == locale_time.am_pm[1]:
  357.             if hour != 12:
  358.                 hour += 12
  359.             
  360.         
  361.         if group_key == 'M':
  362.             minute = int(found_dict['M'])
  363.             continue
  364.         if group_key == 'S':
  365.             second = int(found_dict['S'])
  366.             continue
  367.         if group_key == 'f':
  368.             s = found_dict['f']
  369.             s += '0' * (6 - len(s))
  370.             fraction = int(s)
  371.             continue
  372.         if group_key == 'A':
  373.             weekday = locale_time.f_weekday.index(found_dict['A'].lower())
  374.             continue
  375.         if group_key == 'a':
  376.             weekday = locale_time.a_weekday.index(found_dict['a'].lower())
  377.             continue
  378.         if group_key == 'w':
  379.             weekday = int(found_dict['w'])
  380.             if weekday == 0:
  381.                 weekday = 6
  382.             else:
  383.                 weekday -= 1
  384.         if group_key == 'j':
  385.             julian = int(found_dict['j'])
  386.             continue
  387.         if group_key in ('U', 'W'):
  388.             week_of_year = int(found_dict[group_key])
  389.             if group_key == 'U':
  390.                 week_of_year_start = 6
  391.             else:
  392.                 week_of_year_start = 0
  393.         if group_key == 'Z':
  394.             found_zone = found_dict['Z'].lower()
  395.             for value, tz_values in enumerate(locale_time.timezone):
  396.                 if (found_zone in tz_values or time.tzname[0] == time.tzname[1]) and time.daylight and found_zone not in ('utc', 'gmt'):
  397.                     break
  398.                 else:
  399.                     tz = value
  400.                     break
  401.             
  402.     leap_year_fix = False
  403.     if year is None and month == 2 and day == 29:
  404.         year = 1904
  405.         leap_year_fix = True
  406.     elif year is None:
  407.         year = 1900
  408.     if julian == -1 and week_of_year != -1 and weekday != -1:
  409.         week_starts_Mon = True if week_of_year_start == 0 else False
  410.         julian = _calc_julian_from_U_or_W(year, week_of_year, weekday, week_starts_Mon)
  411.     if julian == -1:
  412.         julian = (datetime_date(year, month, day).toordinal() - datetime_date(year, 1, 1).toordinal()) + 1
  413.     else:
  414.         datetime_result = datetime_date.fromordinal((julian - 1) + datetime_date(year, 1, 1).toordinal())
  415.         year = datetime_result.year
  416.         month = datetime_result.month
  417.         day = datetime_result.day
  418.     if weekday == -1:
  419.         weekday = datetime_date(year, month, day).weekday()
  420.     if leap_year_fix:
  421.         year = 1900
  422.     return (time.struct_time((year, month, day, hour, minute, second, weekday, julian, tz)), fraction)
  423.  
  424.  
  425. def _strptime_time(data_string, format = '%a %b %d %H:%M:%S %Y'):
  426.     return _strptime(data_string, format)[0]
  427.  
  428.